﻿using System.Text;
using System.Web.Caching;
using Nasa8x.Mvc.Controls;

namespace System.Web.Mvc
{

        //http://coderjournal.com/2008/03/aspnet-mvc-captcha/
        public static class CaptchaHelper
        {
            /// <summary>
            /// Captchas the text box.
            /// </summary>
            /// <param name="helper">The helper.</param>
            /// <param name="name">The name.</param>
            /// <returns></returns>
            public static string CaptchaTextBox(this HtmlHelper helper, string name)
            {
                return String.Format(@"<input type=""text"" id=""{0}"" name=""{0}"" value="""" maxlength=""{1}"" autocomplete=""off"" />",
                    name, Nasa8x.Mvc.Controls. CaptchaImage.TextLength
                    );

            }

            /// <summary>
            /// Generates the captcha image.
            /// </summary>
            /// <param name="helper">The helper.</param>
            /// <param name="height">The height.</param>
            /// <param name="width">The width.</param>
            /// <returns>
            /// Returns the <see cref="Uri"/> for the generated <see cref="CaptchaImage"/>.
            /// </returns>
            public static string CaptchaImage(this HtmlHelper helper, int height, int width)
            {
                var image = new CaptchaImage
                {
                    Height = height,
                    Width = width,
                };

                HttpRuntime.Cache.Add(
                    image.UniqueId,
                    image,
                    null,
                    DateTime.Now.AddSeconds(Nasa8x.Mvc.Controls.CaptchaImage.CacheTimeOut),
                    Cache.NoSlidingExpiration,
                    CacheItemPriority.NotRemovable,
                    null);

                var stringBuilder = new StringBuilder(256);
                stringBuilder.Append("<input type=\"hidden\" name=\"captcha-guid\" value=\"");
                stringBuilder.Append(image.UniqueId);
                stringBuilder.Append("\" />");
                stringBuilder.AppendLine();
                stringBuilder.Append("<img src=\"");
                stringBuilder.Append("captcha.ashx?guid=" + image.UniqueId);
                stringBuilder.Append("\" alt=\"CAPTCHA\" width=\"");
                stringBuilder.Append(width);
                stringBuilder.Append("\" height=\"");
                stringBuilder.Append(height);
                stringBuilder.Append("\" />");

                return stringBuilder.ToString();
            }
        }
 
    }
